package com.example.demo.service.impl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.entity.Goods;
import com.example.demo.model.entity.User;
import com.example.demo.model.enums.ResultCodeEnum;
import com.example.demo.model.request.user.UserLoginRequest;
import com.example.demo.model.request.user.UserRegisterRequest;
import com.example.demo.model.request.user.UserSetBlackRequest;
import com.example.demo.model.response.PageQueryGoodsResponse;
import com.example.demo.model.response.PageQueryUserResponse;
import com.example.demo.service.UserService;
import com.example.demo.util.PageInfo;
import com.example.demo.util.PageUtil;
import com.example.demo.util.PromotionException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    public Boolean register(UserRegisterRequest request) {
        String userName = request.getUserName();
        String password = request.getPassword();
        String phoneNumber = request.getPhoneNumber();

        //账号密码合法性校验
        if (userName.length() > 32 || password.length() > 32) {
            throw PromotionException.fail(ResultCodeEnum.PARAM_ILEEGAL);
        }
        String regexPattern = "^[A-Za-z0-9.]+$";
        Pattern pattern = Pattern.compile(regexPattern);
        Matcher matcher = pattern.matcher(userName);
        if (!matcher.find()) {
            throw PromotionException.fail(ResultCodeEnum.USER_NAME_INVALID);
        }
        //账号幂等校验
        User existUser = userMapper.selectByUserName(userName);
        if (existUser != null) {
            throw PromotionException.fail(ResultCodeEnum.USER_NAME_EXISTED);
        }

        //密码md5加密
        String md5Password = DigestUtils.md5Hex(password);
        User user = new User();
        user.setUserName(userName);
        user.setPassword(md5Password);
        user.setPhoneNumber(phoneNumber);
        user.setAdmin(false);
        userMapper.insertUser(user);
        return true;
    }

    @Override
    public User login(UserLoginRequest request) {
        String userName = request.getUserName();
        String password = request.getPassword();

        //查询账号
        User existUser = userMapper.selectByUserName(userName);
        if (null == existUser) {
            throw PromotionException.fail(ResultCodeEnum.USER_NAME_NOT_EXISTED);
        }

        //密码匹配
        String md5Password = DigestUtils.md5Hex(password);
        if (!md5Password.equals(existUser.getPassword())) {
            throw PromotionException.fail(ResultCodeEnum.PASSWORD_NOT_MATCHED);
        }
        return existUser;
    }

    @Override
    public PageQueryUserResponse pageQuery(PageInfo pageInfo) {
        PageQueryUserResponse response = new PageQueryUserResponse();

        //分页查询用户
        Integer offset = pageInfo.getPageSize() * (pageInfo.getCurrent() - 1);
        List<User> goodsList = userMapper.pageQuery(pageInfo.getPageSize(), offset);
        response.setItems(goodsList);

        //查询总记录条数,并设置分页信息
        long totalItem = userMapper.getCount();
        setPageInfo(response, totalItem, pageInfo.getCurrent(), pageInfo.getPageSize());
        return response;
    }

    @Override
    public Boolean setBlack(UserSetBlackRequest request) {
        User existUser = userMapper.selectById(request.getUserId());
        if (null == existUser) {
            throw PromotionException.fail(ResultCodeEnum.USER_NAME_NOT_EXISTED);
        }
        userMapper.setBlack(request.getUserId());
        return true;
    }

    /**
     * 设置response的分页信息
     *
     * @param response
     * @param totalItem
     * @param current
     * @param pageSize
     */
    private void setPageInfo(PageQueryUserResponse response, long totalItem, int current, int pageSize) {
        response.setTotal(totalItem);
        response.setCurrent(current);
        response.setPageSize(pageSize);
        response.setTotalPage(PageUtil.calculateTotalPage(totalItem, pageSize));
    }
}
